package com.zrc.japktool.ui;

import com.zrc.japktool.apk.check.CheckGame;
import com.zrc.japktool.ui.view.RichTextFXLogView;
import com.zrc.japktool.ui.view.WebLogView;
import com.zrc.japktool.util.DialogUtil;
import com.zrc.japktool.util.TaskLog;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.util.*;

public class Tab0Controller_CheckGame {
    private boolean isRunner = false;
    @FXML
    private TextField apkPath_TextField;
    @FXML
    private VBox rootVBox;
    @FXML
    private RichTextFXLogView logView;
    private TaskLog log = new TaskLog() {

        @Override
        public void info(String msg) {logView.info(msg);}

        @Override
        public void warn(String msg) {logView.warn(msg);}

        @Override
        public void debug(String msg) {logView.debug(msg);}

        @Override
        public void error(String msg) {logView.error(msg);}

        @Override
        public void tip(String msg) {logView.tip(msg);}
    };

    @FXML
    public void initialize() {
        logView.tip("等待操作...");// 初始化日志区域
        setupDragAndDrop();// 设置拖放事件处理器
    }

    private void setupDragAndDrop() {
        rootVBox.setOnDragOver(event -> {
            Dragboard db = event.getDragboard();
            if (db.hasFiles()) {
                boolean hasValidFile = db.getFiles().stream().anyMatch(file -> file.getName().toLowerCase().endsWith(".apk") || file.getName().toLowerCase().endsWith(".xapk"));// 检查文件扩展名
                if (hasValidFile) {
                    event.acceptTransferModes(TransferMode.COPY);
                }
            }
            event.consume();
        });

        rootVBox.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
                List<File> files = db.getFiles();
                for (File file : files) { // 只处理第一个有效的APK文件
                    String fileName = file.getName().toLowerCase();
                    String filePath = file.getAbsolutePath().replace("\\", "/");
                    if (fileName.endsWith(".apk") || fileName.endsWith(".xapk")) {
                        apkPath_TextField.setText(filePath);
                        logView.tip("拖放文件: " + filePath);
                        success = true;
                        break;
                    }
                }
            }
            event.setDropCompleted(success);
            event.consume();
        });
    }

    @FXML
    private void handleFileSelection() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择APK文件");

        // 设置文件过滤器
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("apk文件 (*.apk)", "*.apk,*.xapk");
        fileChooser.getExtensionFilters().add(extFilter);

        // 获取当前窗口
        Stage stage = (Stage) logView.getScene().getWindow();
        File selectedFile = fileChooser.showOpenDialog(stage);

        if (selectedFile != null) {
            String filePath = selectedFile.getAbsolutePath().replace("\\", "/");
            apkPath_TextField.setText(filePath);
            logView.tip("已选择文件: " + filePath);
        } else {
            logView.tip("文件选择已取消");
        }
    }

    @FXML
    public void fakerApk() {

        if (isRunner) {
            logView.error("当前任务正在进行: 请认真等待...");
            DialogUtil.showInfoDialog((Stage)logView.getScene().getWindow(),"温馨提示！","当前任务正在进行: 请认真等待...");
            return;
        }

        String filePath = apkPath_TextField.getText();
        if (filePath.isEmpty()) {
            logView.error("错误: 请先选择apk文件");
            return;
        }

        File apkFile = new File(filePath);
        if (!apkFile.exists()) {
            logView.error("错误: 文件不存在 - " + filePath);
            return;
        }

        // 创建一个Task来执行耗时操作
        Task<Void> task = new Task<>() {
            @Override
            protected Void call() {
                isRunner = true;
                logView.clear();
                CheckGame checkGame = new CheckGame(log);
                checkGame.checkGame(filePath);
                isRunner = false;
                return null;
            }
        };

        // 设置任务失败时的处理
        task.setOnFailed(event -> {
            isRunner = false;
            Platform.runLater(() -> {
                Throwable exception = task.getException();
                logView.error("任务执行失败: " + exception.getMessage());
                exception.printStackTrace();
            });
        });

        // 启动后台线程执行任务
        new Thread(task).start();
    }
}